﻿using CommonUtil.Model;
using log4net;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Reflection;
using System.Speech.Synthesis;

namespace CommonUtil
{
    /// <summary>
    /// 语音播报共通
    /// </summary>
    public class SpeechHelper
    {
        /// <summary>
        /// 日志对象
        /// </summary>
        private static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        /// <summary>
        /// 语音播报对象
        /// </summary>
        private SpeechSynthesizer _speech;

        /// <summary>
        /// 是否启用语言播报
        /// </summary>
        private AppConfigInfo configInfo = ConfigManager.getConfigInfo();

        public SpeechSynthesizer speeck
        {
            get
            {
                return _speech;
            }

            set
            {
                _speech = value;
            }
        }

        public SpeechHelper() {
            _speech = new SpeechSynthesizer();
        }

        /// <summary>
        /// 获取系统已安装的声音信息
        /// </summary>
        /// <returns></returns>
        public List<VoiceInfo> getVoiceInfos()
        {
            List<VoiceInfo> voiceList = new List<VoiceInfo>();

            using (SpeechSynthesizer synth = new SpeechSynthesizer())
            {
                foreach (InstalledVoice voice in synth.GetInstalledVoices())
                {
                    voiceList.Add(voice.VoiceInfo);
                }
            }

            return voiceList;
        }

        /// <summary>
        /// 播报语音
        /// </summary>
        /// <param name="speakVal"></param>
        public void SpeakAsync(string speakVal)
        {
            try
            {
                if (!configInfo.SpeechEnabled)
                {
                    return;
                }
                var tmpInfo = getVoiceInfos();
                // Initialize a new instance of the SpeechSynthesizer.
                //SpeechSynthesizer synth = new SpeechSynthesizer();

                // Configure the audio output. 
                _speech.SetOutputToDefaultAudioDevice();
                _speech.SpeakAsync(speakVal);
            }
            catch (Exception e)
            {
                log.Error(e);
            }
        }
    }
}
